<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>
            {{ $t('basic_information') }}
          </p>
        </div>
        <div class="model-panel-body">
          <basic-information
            v-model:ref-obj="infoList.ref"
            :info="infoList"
            :rules="infoList.rules"
          >
            <template v-slot:basic-depotName="scope">
              <el-input
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择领入仓库"
                v-model="infoList.data.depotName"
              >
                <template #append>
                  <el-icon @click="selectDepot"><Search /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:basic-exportDepotName="scope">
              <el-input
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择领出仓库"
                v-model="infoList.data.exportDepotName"
              >
                <template #append>
                  <el-icon @click="selectDepotExport"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:basic-businessDate="scope">
              <el-date-picker
                v-model="infoList.data['businessDate']"
                type="date"
                value-format="YYYY-MM-DD"
                :disabled-date="
                  (time) => {
                    let _time = formatDate(new Date(time), 'YYYY-MM-DD')
                    return _time > disEndDate || _time < disStartDate
                  }
                "
                :clearable="false"
              />
            </template>
          </basic-information>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button
                :disabled="
                  !infoList.data.exportDepotId ||
                  infoList.data.exportDepotId == -2
                "
                @click="addProduct"
                >新增行</el-button
              >
            </template>
            <template v-slot:filter-removeProduct>
              <el-button
                :disabled="
                  !canDeleteProduct ||
                  !infoList.data.exportDepotId ||
                  infoList.data.exportDepotId == -2
                "
                @click="removeProduct"
                >删除行</el-button
              >
            </template>

            <template v-slot:filter-smartRecommendation>
              <el-button
                :disabled="
                  !infoList.data.exportDepotId ||
                  infoList.data.exportDepotId == -2
                "
                @click="_smartRecommendation"
                >智能推荐</el-button
              >
            </template>
            <template v-slot:filter-receivingCodeScan>
              <ScanInputBox
                :query="scanInfo.query"
                :api="scanInfo.api"
                :disabled="
                  !infoList.data.exportDepotId ||
                  infoList.data.exportDepotId == -2
                "
                @callback="onCallBackScanData"
              />
            </template>
          </NewPageFilter>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :class="{
                  isShow:
                    selectProductInfo.popoVisible ||
                    selectBatchInfo.popoVisible,
                }"
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summaryFieldList="tableInfo.summaryFieldList"
                :spanMethod="spanMethod"
                :tabIndex="false"
                :check-box="true"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :cell-class-name="tableCellClassName"
                :isDynamic="true"
                methodKey="productId"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-commonName="scope">
                  <el-input
                    v-if="
                      scope.row.emptyRowType && scope.row.emptyRowType === '1'
                    "
                    :ref="'productRef' + scope.$index"
                    :class="'productKey' + scope.$index"
                    class="productKey"
                    :disabled="
                      !infoList.data.exportDepotId ||
                      infoList.data.exportDepotId == -2
                    "
                    placeholder="名称\编码\规格\批号"
                    v-model="scope.row.productKeyword"
                    @keyup.enter="productSearchInput(scope.row, scope.$index)"
                  >
                    <template #append>
                      <div
                        class="el-input-search"
                        @click="productSearch(scope.row, scope.$index)"
                      >
                        <el-icon style="vertical-align: middle">
                          <Search />
                        </el-icon>
                      </div>
                    </template>
                  </el-input>
                  <span v-else>{{ scope.row.commonName }}</span>
                </template>
                <template v-slot:col-batchNumber="scope">
                  <el-input
                    v-if="
                      scope.row.emptyRowType &&
                      (scope.row.emptyRowType === '1' ||
                        scope.row.emptyRowType === '2') &&
                      (infoList.data.isCargoSpaceManage == 1
                        ? scope.row.emptyRowType
                        : !scope.row.codeType ||
                          scope.row.codeType === 1 ||
                          scope.row.codeType === 4)
                    "
                    :ref="'batchRef' + scope.$index"
                    :class="'batchKey' + scope.$index"
                    class="batchKey"
                    :disabled="
                      !scope.row.productId ||
                      !infoList.data.exportDepotId ||
                      infoList.data.exportDepotId == -2
                    "
                    placeholder="批号\入库批次\供应商名称"
                    v-model="scope.row.batchKeyword"
                    @keyup.enter="
                      batchNumberSearchInput(scope.row, scope.$index)
                    "
                  >
                    <template #append>
                      <div
                        class="el-input-search"
                        @click="batchNumberSearch(scope.row, scope.$index)"
                      >
                        <el-icon style="vertical-align: middle">
                          <Search />
                        </el-icon>
                      </div>
                    </template>
                  </el-input>
                  <template v-else>
                    <StoreBatchNumberTag :row="scope.row" str="batchNumber" />
                  </template>
                </template>
                <template v-slot:col-qty="scope">
                  <el-form-item
                    v-if="
                      infoList.data.isCargoSpaceManage == 1
                        ? !scope.row.emptyRowType
                        : (scope.row.codeType === 1 ||
                            scope.row.codeType === 4) &&
                          !scope.row.emptyRowType
                    "
                    class="margin-bottom"
                  >
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: (rule, value, callback) =>
                                        positiveAndZero(
                                          rule,
                                          value,
                                          callback,
                                          scope.row
                                        ),
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              v-model.lazy="scope.row.largeUnitQty"
                              style="width: 100%; margintop: 18px"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              :min="0"
                              :max="largeMax(scope.row)"
                              @change="
                                changeLarge(
                                  $event,
                                  scope.row,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                            />
                          </el-form-item>
                          <!-- <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div> -->
                        </div>
                        <div
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                          class="page-table-input-number-item"
                        >
                          <el-form-item>
                            <el-input-number
                              v-model.lazy="scope.row.smallUnitQty"
                              style="width: 100%; margintop: 18px"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="smallMax(scope.row)"
                            />
                          </el-form-item>
                          <!-- <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div> -->
                        </div>
                      </div>
                      <div
                        v-if="scope.row.qtyOperateMode === 2"
                        class="page-table-input-number-right"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                  <span
                    v-else-if="
                      infoList.data.isCargoSpaceManage == 1
                        ? false
                        : (scope.row.codeType === 2 ||
                            scope.row.codeType === 3) &&
                          !scope.row.emptyRowType
                    "
                    >{{ $fn.qtyFormatter(scope.row.qty) }}</span
                  >
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <SelectProduct
      v-if="selectProductInfo.visible"
      v-model:showDialog="selectProductInfo.visible"
      :tableKey="selectProductInfo.tableKey"
      :query="selectProductInfo.query"
      :api="selectProductInfo.api"
      :highlightRow="false"
      :checkBox="true"
      :showPrice="$permission('useAudit:price')"
      @callback="selectProductBackList"
    />
    <SelectBatch
      v-if="selectBatchInfo.visible"
      v-model:showDialog="selectBatchInfo.visible"
      :popoVisible="selectBatchInfo.visible"
      :tableKey="selectBatchInfo.tableKey"
      :api="selectBatchInfo.api"
      :query="selectBatchInfo.query"
      :codeType="selectBatchInfo.row.codeType"
      :highlightRow="false"
      :checkBox="true"
      :showPrice="$permission('useAudit:price')"
      @callback="selectBatchBackList"
    ></SelectBatch>
    <el-popover
      v-if="selectProductInfo.popoVisible"
      ref="productPopoverRef"
      popper-class="popover-wrapper"
      placement="bottom-start"
      :virtual-ref="productRef"
      width="1000px"
      :visible="selectProductInfo.popoVisible"
      virtual-triggering
      @hide="productPopoHide"
    >
      <ProductTable
        v-if="selectProductInfo.popoVisible"
        :popoVisible="selectProductInfo.popoVisible"
        :tableKey="selectProductInfo.tableKey"
        :query="selectProductInfo.query"
        :highlightRow="selectProductInfo.highlightRow"
        :checkBox="selectProductInfo.checkBox"
        :refresh="selectProductInfo.refresh"
        :api="selectProductInfo.api"
        :showPrice="$permission('useAudit:price')"
        tableType="product"
        @checkMore="checkMore('product')"
        @reset="selectProductInfo.popoVisible = false"
        @callback="selectProductBack"
        @keyDown="productKeyDown"
      ></ProductTable>
    </el-popover>
    <el-popover
      v-if="selectBatchInfo.popoVisible"
      ref="batchPopoverRef"
      :virtual-ref="batchRef"
      popper-class="popover-wrapper"
      placement="bottom-start"
      width="780px"
      :visible="selectBatchInfo.popoVisible"
      virtual-triggering
      @hide="batchPopoHide"
    >
      <ProductTable
        v-if="selectBatchInfo.popoVisible"
        :popoVisible="selectBatchInfo.popoVisible"
        :tableKey="selectBatchInfo.tableKey"
        :query="selectBatchInfo.query"
        :highlightRow="selectBatchInfo.highlightRow"
        :checkBox="selectBatchInfo.checkBox"
        :refresh="selectBatchInfo.refresh"
        :api="selectBatchInfo.api"
        :showPrice="$permission('useAudit:price')"
        :codeType="selectBatchInfo.row.codeType"
        tableType="batch"
        @checkMore="checkMore('batch')"
        @reset="selectBatchInfo.popoVisible = false"
        @callback="selectBatchBack"
        @keyDown="batchKeyDown"
      ></ProductTable>
    </el-popover>
    <BatchIndividual
      v-if="individualInfo.visible"
      v-model:visible="individualInfo.visible"
      :leftApi="individualInfo.leftApi"
      :rightApi="individualInfo.rightApi"
      :leftTableKey="individualInfo.leftTableKey"
      :rightTableKey="individualInfo.rightTableKey"
      :leftQuery="individualInfo.leftQuery"
      :rightQuery="individualInfo.rightQuery"
      :details="individualInfo.details"
      :isGetRightList="!!id"
      :showPrice="$permission('useAudit:price')"
      @callback="individualCallback"
    ></BatchIndividual>
    <SelectDepot
      v-if="depotInfo.visible"
      v-model:showDialog="depotInfo.visible"
      @callback="selectDepotCallback"
      :saveEmpty="true"
      :checkBox="false"
      :query="depotInfo.query"
      :highlightRow="true"
    />
    <SelectDepot
      v-if="exportDepotInfo.visible"
      v-model:showDialog="exportDepotInfo.visible"
      @callback="selectExportDepotCallback"
      :saveEmpty="true"
      :checkBox="false"
      :api="exportDepotInfo.api"
      :query="exportDepotInfo.query"
      :highlightRow="true"
    />
  </div>
</template>

<script setup name="useApplicationExport">
import PageTable from '@/components/PageTable/index'
import BasicInformation from '@/components/BasicInformation/index'
import SelectProduct from '../components/SelectProduct'
import ScanInputBox from '../components/ScanInputBox'
import SelectBatch from '../components/SelectBatch'
import BatchIndividual from '../components/BatchIndividual'
import ProductTable from '../components/ProductTable'
import StoreBatchNumberTag from '@/views/stock/components/StoreBatchNumberTag'
import {
  getUseApplication,
  createUseExport,
  commitAndBatchOutBound,
  exportUseApplication,
  printUseApplication,
  smartRecommendation,
  getUseApplicationDetail,
  useAuditGetDepots,
  getUseAuditGetDefaultExportDepot,
} from '@/api/use'
import {
  customizeScanWithForbidden,
  otherExportOrderDetailsCustomizeListAll,
  getDepotStockCustomizeListPage,
  depotStockValidateOptimalValidate,
} from '@/api/stock'
import { getCoreSystemConfigAll } from '@/api/core'
import { getCustomizeSetting } from '@/api/customize'
import { setVal, setTabindex } from '@/common/js/base'
import moment from 'moment'
import _ from 'lodash'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
import { formatDate } from '@/utils/index'
const { proxy } = getCurrentInstance()
const emit = defineEmits()

const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))
const props = defineProps(['visible', 'title', 'id'])

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const index = ref('')
const productIds = ref([])
const selectRows = ref([])
const storageData = ref([])
const chooseIndex = ref([])
const totalRows = ref([])
const tableData = ref([])
const productPopoverRef = ref()
const productRef = ref()
const batchPopoverRef = ref()
const batchRef = ref()
const formRefs = ref()
const applicationDetailProductIds = ref('')
const positiveAndZero = (rule, value, callback, row) => {
  const reg = /^(0|[1-9]\d{0,8})(\s|$|\.\d{0,}\b)/
  let qty_show_precision = systemConfig.value.qty_show_precision || 0
  let maxValue = 0
  tableInfo.data.forEach((item) => {
    if (item.productId === row.productId) {
      maxValue = proxy.$fn.accAdd(item.calcQty || 0, maxValue)
    }
  })
  const pattern = new RegExp('^\\d+.?\\d{0,' + qty_show_precision + '}$')
  if (!reg.test(value)) {
    callback(new Error('输入大于等于0的数字'))
  } else if (!pattern.test(value)) {
    callback(new Error(`小数点后最多只能输入${qty_show_precision}位`))
  } else if (maxValue > row.availableCalcQty) {
    callback(new Error('产品输入的数量之和不能大于' + row.availableCalcQty))
  } else {
    callback()
  }
}
const scanInfo = reactive({
  api: customizeScanWithForbidden,
  query: {
    queryMap: {
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    customizeUserVO: {},
    queryParams: {
      depotId: '',
    },
  },
})
const infoList = reactive({
  ref: null,
  supDepotIds: proxy.$store.state.user.userInfo.coreResourcesVO
    ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
        '1'
      ) !== -1 &&
      proxy.$store.state.user.userInfo.coreResourcesVO.isCargoSpaceManage !== 1
      ? proxy.$store.state.user.userInfo.coreResourcesVO.supDepotIds || []
      : ''
    : '',
  data: {
    exportDepotName: '',
    exportDepotId: '',
  },
  fieldList: [
    { label: '申请单号', value: 'orderNo', type: 'text' },
    { label: '领用人', value: 'createUserName', type: 'text' },
    { label: '领用部门', value: 'deptName', type: 'text' },
    { label: '领入仓库', value: 'depotName', type: 'slot' },
    { label: '领出仓库', value: 'exportDepotName', type: 'slot' },
    { label: '业务日期', value: 'businessDate', type: 'slot' },
  ],
  rules: {
    exportDepotName: [
      { required: true, message: '请领出仓库', target: 'change' },
    ],
    businessDate: [
      { required: true, message: '请选择业务日期', target: 'change' },
    ],
  },
  TimePickerOptions: {},
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'smartRecommendation', show: true },
    { type: 'slot', value: 'receivingCodeScan', show: false },
  ],
})
const detailFilterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {
      isCargoSpaceManage: 0,
    },
  },
})
const depotInfo = reactive({
  visible: false,
  depotType: '',
  api: useAuditGetDepots,
  query: {
    useTypeId: '1',
    status: '1',
    depotAuth: 'id',
  },
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  sysGroup: [],
  data: [
    {
      emptyRowType: '1', //1添加产品和批次，2添加批次
      productKeyword: '',
      batchKeyword: '',
      id: new Date().getTime() + (1 + Math.random()),
    },
  ],
  tabList: [],
  tabIndex: 0,
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [
    {
      label: '通用名称',
      value: 'commonName',
      type: 'slot',
      minWidth: '100px',
    },
    {
      label: '产品编码',
      value: 'productCode',
      width: '100px',
    },
    {
      label: '规格',
      value: 'standard',
    },
    {
      label: '厂家',
      value: 'brandName',
      width: '80px',
    },
    {
      label: '单位',
      value: 'unitName',
      width: '80px',
    },
    {
      label: '申领数',
      value: 'applicationQty',
      width: '60px',
    },
    {
      label: '待出数',
      value: 'availableQty',
      width: '60px',
    },
    {
      label: '批号',
      value: 'batchNumber',
      type: 'slot',
      align: 'left',
      minWidth: '100px',
    },
    {
      label: '生产日期',
      value: 'productionDate',
      width: '80px',
    },
    {
      label: '失效日期',
      value: 'validityDate',
      width: '80px',
    },
    {
      label: '入库批次号',
      value: 'storeBatchNumber',
    },
    {
      label: '供应商',
      value: 'supplierName',
    },
    {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('consume:price'),
      width: '60px',
    },
    {
      label: '可用数',
      value: 'stockAvailableQty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
      width: '60px',
    },

    {
      label: '出库数量',
      value: 'qty',
      type: 'slot',
      width: '170px',
    },
    {
      label: '出库金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('useAudit:price'),
      width: '80px',
    },
  ],
  handle: {
    fixed: 'right',
    label: '批次操作',
    width: '120',
    btList: [
      {
        label: '个体详情',
        event: individualDetails,
        show: true,
        ifRender: ifRenderIndividual,
        // ifRender: function (row) {isCargoSpaceManage
        //   let arr = [2, 3]
        //   return arr.includes(row.codeType) && row.emptyRowType !== '1'
        // },
      },
      {
        label: '新增',
        event: addBucth,
        show: true,
        ifRender: ifRenderAddButch,
      },
      {
        label: '删除',
        event: removeBatch,
        show: true,
        ifRender: function (row) {
          return (
            !row.emptyRowType &&
            infoList.data.exportDepotId &&
            infoList.data.exportDepotId !== -2
          )
        },
      },
    ],
  },
  bigWidth: {
    productCode: '100px',
    standard: '60px',
    brandName: '80px',
    unitName: '80px',
    applicationQty: '60px',
    availableQty: '60px',
    productionDate: '80px',
    validityDate: '80px',
    storeBatchNumber: '80px',
    supplierName: '80px',
    price: '80px',
    stockAvailableQty: '60px',
    qty: '140px',
    sumAmount: '80px',
  },
  smallWidth: {
    productCode: '90px',
    standard: '60px',
    brandName: '60px',
    unitName: '40px',
    applicationQty: '40px',
    availableQty: '40px',
    productionDate: '50px',
    validityDate: '80px',
    storeBatchNumber: '60px',
    supplierName: '60px',
    price: '50px',
    stockAvailableQty: '50px',
    qty: '90px',
    sumAmount: '70px',
  },
})
const fullInfo = reactive({
  btnList: [
    {
      label: '提交并出库',
      event: submitAndexport,
      show: proxy.$permission('useAudit:submitAndexport'),
      disabled: computed(() => {
        return (
          !infoList.data.exportDepotId || infoList.data.exportDepotId === -2
        )
      }),
    },
    {
      label: '提交',
      event: () => submit(),
      show: proxy.$permission('useAudit:submit'),
      disabled: computed(() => {
        return (
          !infoList.data.exportDepotId || infoList.data.exportDepotId === -2
        )
      }),
    },
    { label: '导出excel', event: exportExcel, show: false },
    { label: '打印', event: print, show: false },
  ],
})
const selectProductInfo = ref({
  visible: false,
  popoVisible: false,
  api: undefined,
  refresh: 1,
  row: {},
  index: 0,
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
      productId: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {
      isProductSearchLeft: 1,
      productSearchKey: '',
    },
  },
  tableKey:
    'useApplicationOrduseApplicationOrderRatifyProducterRatifyBatch-com.slip.spd.entity.vo.use.UseApplicationOrderDetailVO',
  highlightRow: true,
  checkBox: false,
})
const selectBatchInfo = ref({
  visible: false,
  popoVisible: false,
  api: undefined,
  refresh: 1,
  row: {},
  index: 0,
  query: {
    queryMap: {
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      orgId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      productId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {
      isDepotSearchSingle: 1,
      stockSearchKey: '',
      groupField: '',
      forbidden: 1,
    },
  },
  tableKey: '', //useApplicationOrderRatifyWmsBatch   useApplicationOrderRatifyBatch-com.slip.spd.entity.vo.stock.DepotStockVO
  highlightRow: true,
  checkBox: false,
})

const individualInfo = ref({
  visible: false,
  row: {},
  details: [],
  index: '',
  leftQuery: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      orgId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      productId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {
      isDepotSearchRight: 1,
      groupField: '',
      forbidden: 1,
    },
  }, //个体弹窗左边数据查询条件
  rightQuery: {
    queryMap: {
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {},
  }, //个体弹窗右边数据查询条件
  leftTableKey:
    'useApplicationOrderRatifyProductIndividualLeft-com.slip.spd.entity.vo.stock.DepotStockVO',
  rightTableKey:
    'useApplicationOrderRatifyProductIndividuaRight-com.slip.spd.entity.vo.stock.DepotStockVO',
  rightApi: otherExportOrderDetailsCustomizeListAll, //个体弹窗右边数据接口
  leftApi: getDepotStockCustomizeListPage, //个体弹窗左边数据接口
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canDeleteProduct = computed(() => {
  return tableInfo.selections.length
})
watch(
  () => tableInfo.data,
  (val) => {
    console.log('tab', tableInfo.data)
    if (val.length) {
      let list = []
      val.forEach((item, index) => {
        if (item.emptyRowType && item.emptyRowType === '1') {
          let arr = [
            { key: 'productKey' + index, index: index },
            { key: 'batchKey' + index, index: index },
          ]
          list = list.concat(arr)
        } else if (item.emptyRowType && item.emptyRowType === '2') {
          list.push({ key: 'batchKey' + index, index: index })
        }
      })
      tableInfo.tabList = list
      setTabindex(proxy)
      setSuplierIdMap()
    }
  },
  { deep: true }
)
watch(
  () => selectBatchInfo.value.popoVisible,
  (val) => {
    if (val) {
      selectProductInfo.value.popoVisible = false
    }
  }
)
watch(
  () => selectProductInfo.value.popoVisible,
  (val) => {
    if (val) {
      selectBatchInfo.value.popoVisible = false
    }
  }
)
let disStartDate = ref('')
let disEndDate = ref('')
// setDisableTime(infoList.fieldList, disStartDate, disEndDate)
async function setBusinessDate() {
  infoList.data.businessDate = await _getCurrentFiscalPeriod(
    infoList.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
  // infoList.fieldList.forEach((item) => {
  //   if (item.value === 'businessDate') {
  //     infoList.TimePickerOptions = item.TimePickerOptions
  //   }
  // })
}
window.addEventListener('click', closePopper, { passive: true })
window.addEventListener('keydown', addTab, true)
onActivated(() => {
  window.addEventListener('click', closePopper, { passive: true })
  window.addEventListener('keydown', addTab, true)
})
onDeactivated(() => {
  window.removeEventListener('click', closePopper, true)
  window.removeEventListener('keydown', addTab, true)
})
function addTab(val) {
  /* if (val.key === 'Tab') {
    let list = tableInfo.tabList
    let listIndex = list[tableInfo.tabIndex]
    if (!listIndex) {
      return
    }
    let item = tableInfo.data[listIndex.index]
    if (item.emptyRowType && item.emptyRowType === '1') {
      selectProductInfo.value.visible = false
      selectProductInfo.value.visible = false
      selectBatchInfo.value.visible = false
      selectBatchInfo.value.popoVisible = false
      let timer = setTimeout(() => {
        document
          .getElementsByClassName(
            'productKey' + list[tableInfo.tabIndex].index
          )[0]
          ?.querySelector('.el-input__inner')
          .focus()
        productSearchInput(item, list[tableInfo.tabIndex].index)
        clearTimeout(timer)
      }, 0)
    } else if (item.emptyRowType && item.emptyRowType === '2') {
      selectProductInfo.value.visible = false
      selectProductInfo.value.visible = false
      selectBatchInfo.value.visible = false
      selectBatchInfo.value.popoVisible = false
      let timer = setTimeout(() => {
        document
          .getElementsByClassName(
            'batchKey' + list[tableInfo.tabIndex].index
          )[0]
          ?.querySelector('.el-input__inner')
          .focus()
        batchNumberSearchInput(item, list[tableInfo.tabIndex].index)
        clearTimeout(timer)
      }, 0)
    }
    tableInfo.tabIndex++
    if (tableInfo.tabIndex >= list.length) {
      tableInfo.tabIndex = 0
    }
    return
  } */
}
function closePopper(e) {
  if (
    e.target.closest('.el-popper') ||
    e.target.closest('.productKey') ||
    e.target.closest('.batchKey')
  ) {
    // 点击当前元素处理操作
  } else {
    //点击非当前元素，需要执行的代码
    selectBatchInfo.value.popoVisible = false
    selectProductInfo.value.popoVisible = false
  }
}
const canSave = computed(() => {
  return tableInfo.data.length
})
const canAddProduct = computed(() => {
  return infoList.data.exportDepotId && infoList.data.exportDepotId !== -2
})
const canRemoveProduct = computed(() => {
  return tableInfo.selections.length
})

const exportDepotInfo = reactive({
  visible: false,
  depotType: '',
  api: useAuditGetDepots,
  query: {
    useTypeId: '1',
    status: '1',
    idMult: '',
    idNot: '',
    depotAuth: 'id',
  },
})

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], infoList.ref]
  proxy.$nextTick(() => {
    if (!props.id) {
      infoList.fieldList = infoList.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
  proxy.$fn.setFieldListColWidth(
    tableInfo.fieldList,
    tableInfo.bigWidth,
    tableInfo.smallWidth
  )
})
function selectDepotExport() {
  // exportDepotInfo.depotType = 'export'
  // exportDepotInfo.query.orderId = infoList.data.id
  // exportDepotInfo.query.storeDepotId = infoList.data.depotId
  // exportDepotInfo.visible = true
  exportDepotInfo.depotType = 'export'
  exportDepotInfo.query.idMult = infoList.supDepotIds?.length
    ? infoList.supDepotIds.toString()
    : ''
  exportDepotInfo.query.orderId = infoList.data.id
  exportDepotInfo.query.storeDepotId = infoList.data.depotId
  if (!infoList.data.depotId || infoList.data.depotId == '-2') {
    exportDepotInfo.query.idNot = infoList.data.exportDepotId
  } else {
    exportDepotInfo.query.idNot =
      infoList.data.depotId +
      (infoList.data.exportDepotId ? ',' + infoList.data.exportDepotId : '')
  }
  exportDepotInfo.visible = true
}

function selectExportDepotCallback(row) {
  if (row && row.id) {
    infoList.data.exportDepotId = row.id
    infoList.data.exportDepotName = row.name
    infoList.data.exportDeptName = row.deptName
    infoList.data.exportDeptId = row.deptId
    individualInfo.value.leftQuery.queryMap.depotId.value = row.id
    scanInfo.query.queryParams.depotId = row.id
    selectBatchInfo.value.query.queryMap.depotId.value = row.id
  } else {
    infoList.data.exportDepotId = ''
    infoList.data.exportDepotName = ''
    infoList.data.exportDeptName = ''
    infoList.data.exportDeptId = ''
    individualInfo.value.leftQuery.queryMap.depotId.value = ''
    scanInfo.query.queryParams.depotId = ''
    selectBatchInfo.value.query.queryMap.depotId.value = ''
  }
  tableInfo.data = []
  tableData.value = []
  getList()
}
function selectDepot() {
  depotInfo.depotType = 'export'
  depotInfo.query.deptId = infoList.data.deptId
  depotInfo.visible = true
}
function selectDepotCallback(row) {
  if (row) {
    infoList.data.depotId = row.id
    infoList.data.depotName = row.name
    infoList.supDepotIds = row.supDepotIds
    infoList.data.exportDepotId = ''
    infoList.data.exportDepotName = ''
    getList()
  } else {
    infoList.data.depotId = ''
    infoList.data.depotName = ''
    infoList.supDepotIds = []
    getList()
  }
}
function spanMethod({ row, column, rowIndex, columnIndex }) {
  let len = tableInfo.fieldList.length
  let isCargoSpaceManage = infoList.data.isCargoSpaceManage //1货位管理，0非货位管理
  if (row.emptyRowType !== '1' || !row.emptyRowType) {
    let afterIndexs = []
    if (isCargoSpaceManage == 0) {
      afterIndexs = row.codeType === 2 || row.codeType === 3 ? [len + 1] : []
    }
    let keys = new Array(len + 2)
    if (afterIndexs.length && afterIndexs.includes(columnIndex)) {
      keys[columnIndex] = 'productId'
    } else {
      keys = [
        'productId',
        'commonName',
        'productCode',
        'standard',
        'brandName',
        'unitName',
        'applicationQty',
        'availableQty',
      ]
    }
    // 注意:字段列表要按表格排列的顺序排列,如果后续字段不再需要进行行合并,可以省略后面的字段,如果中间某字段要跳过合并,要用空字符串顶位
    return proxy.$fn.spanMethod(tableInfo.data, keys, rowIndex, columnIndex)
  }
}
function ifRenderAddButch(row) {
  let isCargoSpaceManage = infoList.data.isCargoSpaceManage //1货位管理，0非货位管理
  let arr = []
  if (isCargoSpaceManage == 1) {
    arr = [1, 2, 3, 4]
  } else if (isCargoSpaceManage == 0) {
    arr = [1, 4]
  }
  if (arr.includes(row.codeType)) {
    let list = tableInfo.data.filter((item) => item.productId === row.productId)
    let index = list.findIndex((item) => item._key === row._key)
    return (
      index === list.length - 1 &&
      infoList.data.exportDepotId &&
      infoList.data.exportDepotId !== -2
    )
  }
}
function ifRenderIndividual(row) {
  let isCargoSpaceManage = infoList.data.isCargoSpaceManage
  if (isCargoSpaceManage == 1) {
    return false
  } else if (isCargoSpaceManage == 0) {
    let arr = [2, 3]
    return (
      arr.includes(row.codeType) &&
      row.emptyRowType !== '1' &&
      infoList.data.exportDepotId &&
      infoList.data.exportDepotId !== -2
    )
  }
}
//新增行
function addProduct() {
  tableInfo.data.push({
    emptyRowType: '1',
    productKeyword: '',
    batchKeyword: '',
    id: new Date().getTime() + (1 + Math.random()),
  })
}
function checkMore(str) {
  if (str === 'product') {
    let row = selectProductInfo.value.row
    let index = selectProductInfo.value.index
    productSearch(row, index)
  } else if (str === 'batch') {
    let row = selectBatchInfo.value.row
    let index = selectBatchInfo.value.index
    batchNumberSearch(row, index)
  }
}
function productSearch(row, index) {
  //产品点击查询图标
  selectProductInfo.value.query.queryParams.productSearchKey =
    row.productKeyword
  selectProductInfo.value.row = row
  selectProductInfo.value.index = index
  let ids = []
  if (tableInfo.data.length) {
    tableInfo.data.forEach((item) => {
      if (item.productId) {
        ids.push(item.productId)
      }
    })
  }
  selectProductInfo.value.query.queryMap.productId.value = ids.length
    ? ids.toString()
    : ''
  selectProductInfo.value.api = getUseApplicationDetail
  selectProductInfo.value.visible = true
  selectProductInfo.value.popoVisible = false
}

function productSearchInput(row, index) {
  //产品enter查询
  productRef.value = proxy.$refs['productRef' + index]
  selectProductInfo.value.query.queryParams.productSearchKey =
    row.productKeyword
  selectProductInfo.value.refresh = Math.random()
  selectProductInfo.value.row = row
  selectProductInfo.value.index = index
  let ids = []
  if (tableInfo.data.length) {
    tableInfo.data.forEach((item) => {
      if (item.productId) {
        ids.push(item.productId)
      }
    })
  }
  selectProductInfo.value.query.queryMap.productId.value = ids.length
    ? ids.toString()
    : ''
  selectProductInfo.value.api = getUseApplicationDetail
  selectProductInfo.value.popoVisible = true
}
function productKeyDown(index) {
  proxy.$nextTick(() => {
    if (index < 0) {
      let className = 'productKey' + selectProductInfo.value.index
      setVal(className)
      selectProductInfo.value.popoVisible = false
      return
    }
    let className = 'productKey' + selectProductInfo.value.index
    let productKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    productKeyDom.blur()
  })
}
function selectProductBack(obj) {
  let index = selectProductInfo.value.index
  tableInfo.data[index] = {
    commonName: obj.commonName,
    productCode: obj.productCode,
    groupConcatIds: obj.groupConcatIds,
    standard: obj.standard,
    brandName: obj.brandName,
    brandId: obj.brandId,
    unitName: obj.unitName,
    unitId: obj.unitId,
    codeTypeValue: obj.codeTypeValue,
    codeType: obj.codeType,
    productId: obj.productId,
    applicationQty: obj.applicationQty,
    availableQty: obj.availableQty,
    applicationCalcQty: obj.applicationCalcQty,
    availableCalcQty: obj.availableCalcQty,
    emptyRowType: '2',
    orderSourceDetailId: obj.id,
  }
  let itemList = tableInfo.data.filter((item) => item.emptyRowType === '1')
  if (!itemList.length) {
    tableInfo.data.push({
      emptyRowType: '1',
      productKeyword: '',
      batchKeyword: '',
      id: new Date().getTime() + (1 + Math.random()),
    })
  }
}
function selectProductBackList(data) {
  let index = selectProductInfo.value.index
  let newData = data.map((item) => {
    return {
      commonName: item.commonName,
      productCode: item.productCode,
      groupConcatIds: item.groupConcatIds,
      standard: item.standard,
      brandName: item.brandName,
      brandId: item.brandId,
      unitName: item.unitName,
      unitId: item.unitId,
      codeTypeValue: item.codeTypeValue,
      codeType: item.codeType,
      productId: item.productId,
      applicationQty: item.applicationQty,
      availableQty: item.availableQty,
      applicationCalcQty: item.applicationCalcQty,
      availableCalcQty: item.availableCalcQty,
      emptyRowType: '2',
      orderSourceDetailId: item.id,
    }
  })
  let emptyRowTypeList = tableInfo.data.filter(
    (item) => item.emptyRowType === '1'
  ) //空行条数
  let list = proxy.$fn.deepClone(tableInfo.data)
  let leftList,
    rightList = []
  if (emptyRowTypeList.length > 1) {
    if (index === tableInfo.data.length - 1) {
      //是否最后一条
      leftList = list.slice(0, index)
      rightList = list.slice(index)
    } else {
      leftList = list.slice(0, index)
      rightList = list.slice(index + 1)
    }
  } else {
    leftList = list.slice(0, index)
    rightList = list.slice(index)
  }
  tableInfo.data = leftList.concat(newData).concat(rightList)
}
function productPopoHide() {
  selectProductInfo.value.popoVisible = false
}
function batchNumberSearch(row, index) {
  //批次点击查询图标
  if (!row.productId) return
  let isCargoSpaceManage = infoList.data.isCargoSpaceManage
  selectBatchInfo.value.query.queryParams.stockSearchKey = row.batchKeyword
  selectBatchInfo.value.row = row
  selectBatchInfo.value.index = index
  let list = tableInfo.data.filter((item) => item.productId === row.productId)
  let ids = []
  if (list.length) {
    list.forEach((row) => {
      if (isCargoSpaceManage == 1) {
        if (row.details && row.details.length) {
          row.details.forEach((item) => {
            ids.push(item.groupConcatIds)
          })
        }
      } else {
        if (row.details && row.details.length) {
          row.details.forEach((item) => {
            ids.push(item.depotStockId)
          })
        } else {
          if (props.id && row.groupConcatDepotStockIds) {
            ids.push(row.groupConcatDepotStockIds)
          }
        }
      }
    })
  }
  selectBatchInfo.value.query.queryMap.orgId.value = row.orgId
  selectBatchInfo.value.query.queryMap.productId.value = row.productId
  selectBatchInfo.value.query.queryMap.id.value = ids.length
    ? ids.toString()
    : ''
  selectBatchInfo.value.api = getDepotStockCustomizeListPage
  selectBatchInfo.value.visible = true
  selectBatchInfo.value.popoVisible = false
}
function batchNumberSearchInput(row, index) {
  //批次enter查询
  let timer = setTimeout(() => {
    if (!row.productId) return
    let className = 'batchKey' + index
    let batchKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    batchKeyDom.focus()
    batchRef.value = proxy.$refs['batchRef' + index]
    selectBatchInfo.value.query.queryParams.stockSearchKey = row.batchKeyword
    selectBatchInfo.value.refresh = Math.random()
    selectBatchInfo.value.row = row
    selectBatchInfo.value.index = index
    let list = tableInfo.data.filter((item) => item.productId === row.productId)
    let ids = []
    if (list.length) {
      list.forEach((row) => {
        if (row.details && row.details.length) {
          row.details.forEach((item) => {
            ids.push(item.depotStockId)
          })
        } else {
          if (props.id && row.groupConcatDepotStockIds) {
            ids.push(row.groupConcatDepotStockIds)
          }
        }
      })
    }
    selectBatchInfo.value.query.queryMap.orgId.value = row.orgId
    selectBatchInfo.value.query.queryMap.productId.value = row.productId
    selectBatchInfo.value.query.queryMap.id.value = ids.length
      ? ids.toString()
      : ''
    selectBatchInfo.value.api = getDepotStockCustomizeListPage
    selectBatchInfo.value.popoVisible = true
    clearTimeout(timer)
  }, 0)
}
function batchPopoHide() {
  selectBatchInfo.value.popoVisible = false
}
function selectBatchBack(obj) {
  let index = selectBatchInfo.value.index
  let row = selectBatchInfo.value.row
  obj = countData(proxy.$fn.deepClone(obj))
  if (row.availableCalcQty < obj.calcQty) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: `产品【${obj.commonName}】出库数量大于待出数，请修改！`,
    })
  }
  obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
  obj.orderSourceDetailId = row.orderSourceDetailId
  obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
  tableInfo.data[index] = proxy.$fn.deepClone(obj)
  tableInfo.data[index].details = [proxy.$fn.deepClone(obj)]
  tableInfo.data[index].productId = row.productId
  tableInfo.data[index].applicationQty = row.applicationQty
  tableInfo.data[index].availableQty = row.availableQty
  tableInfo.data[index].applicationCalcQty = row.applicationCalcQty
  tableInfo.data[index].availableCalcQty = row.availableCalcQty
  tableInfo.data[index].groupConcatIds = row.groupConcatIds
}
function selectBatchBackList(data) {
  let row = selectBatchInfo.value.row
  let index = selectBatchInfo.value.index
  data.forEach((item) => {
    item.orderSourceDetailId = row['orderSourceDetailId']
    item = countData(item)
  })

  let groupData = _.groupBy(data, '_key')
  let productIds = Object.keys(groupData)
  let productIdsIn = []
  tableInfo.data.forEach((item) => {
    if (item.productId === row.productId) {
      if (item._key) {
        if (productIds.includes(item._key)) {
          productIdsIn.push(item._key)
          item.details = item.details.concat(groupData[item._key])
          item = countQty(item)
        }
      }
    }
  })
  let list = []
  if (productIdsIn.length) {
    productIds.forEach((item) => {
      if (!productIdsIn.includes(item)) {
        let groupDataItem = groupData[item]
        let obj = proxy.$fn.deepClone(groupDataItem[0])
        obj.details = proxy.$fn.deepClone(groupDataItem)
        obj.groupConcatIds = row.groupConcatIds
        obj.productId = row.productId
        obj = countQty(obj)
        obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
        obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
        obj.applicationQty = row.applicationQty
        obj.availableQty = row.availableQty
        obj.applicationCalcQty = row.applicationCalcQty
        obj.availableCalcQty = row.availableCalcQty
        list.push(obj)
      }
    })
  } else {
    let values = Object.values(groupData)
    values.forEach((item) => {
      let obj = proxy.$fn.deepClone(item[0])
      obj.details = proxy.$fn.deepClone(item)
      obj.groupConcatIds = row.groupConcatIds
      obj.productId = row.productId
      obj = countQty(obj)
      obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
      obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
      obj.applicationQty = row.applicationQty
      obj.availableQty = row.availableQty
      obj.applicationCalcQty = row.applicationCalcQty
      obj.availableCalcQty = row.availableCalcQty
      list.push(obj)
    })
  }
  if (list.length) {
    let newData = tableInfo.data[index]
    let leftList = []
    if (newData._key) {
      leftList = tableInfo.data.slice(0, index + 1)
    } else {
      leftList = tableInfo.data.slice(0, index)
    }
    let rightList = tableInfo.data.slice(index + 1)
    tableInfo.data = leftList.concat(list).concat(rightList)
  }
  let commonName = []
  tableData.value.forEach((row) => {
    let allCalcQty = 0
    tableInfo.data.forEach((item) => {
      if (item.productId === row.productId) {
        allCalcQty = proxy.$fn.accAdd(item.calcQty || 0, allCalcQty)
      }
    })
    if (row.availableCalcQty < allCalcQty) {
      commonName.push(row.commonName)
    }
  })
  if (commonName.length) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: `产品【${commonName}】出库数量大于待出数，请修改！`,
    })
  }
}
function countQty(data) {
  let largeUnitQty = 0
  let smallUnitQty = 0
  let calcQty = 0
  if (data.details && data.details.length) {
    data.details.forEach((el) => {
      largeUnitQty = proxy.$fn.accAdd(largeUnitQty, el.largeUnitQty || 0)
      smallUnitQty = proxy.$fn.accAdd(smallUnitQty, el.smallUnitQty || 0)
      calcQty = proxy.$fn.accAdd(calcQty, el.calcQty || 0)
    })
  }
  data.largeUnitQty = largeUnitQty
  data.smallUnitQty = smallUnitQty
  data.calcQty = calcQty
  data.qty = proxy.$fn.accDiv(calcQty, data.unitConvertCoefficient || 1)
  data.sumAmount = proxy.$fn.accDiv(
    proxy.$fn.accMul(calcQty, data.price || 0),
    data.unitConvertCoefficient || 1
  )
  return data
}
function batchKeyDown(index) {
  proxy.$nextTick(() => {
    if (index < 0) {
      let className = 'batchKey' + selectProductInfo.value.index
      setVal(className)
      selectBatchInfo.value.popoVisible = false
      return
    }
    let className = 'batchKey' + selectBatchInfo.value.index
    let batchKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    batchKeyDom.blur()
  })
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.stockAvailableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.stockAvailableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.stockAvailableCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
  let isCargoSpaceManage = infoList.data.isCargoSpaceManage //1货位管理，0非货位管理
  if (isCargoSpaceManage == 1) {
    row.calcQty = proxy.$fn.accAdd(
      proxy.$fn.accMul(row.largeUnitQty || 0, row.unitConvertCoefficient || 1),
      row.smallUnitQty || 0
    )
    row.qty = proxy.$fn.accDiv(
      row.calcQty || 0,
      row.unitConvertCoefficient || 1
    )
    row.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(row.calcQty || 0, parseFloat(row.price || 0)),
      row.unitConvertCoefficient || 1
    )
    row.details[0].largeUnitQty = row.largeUnitQty
    row.details[0].smallUnitQty = row.smallUnitQty
    row.details[0].calcQty = row.calcQty
    row.details[0].qty = row.qty
    row.details[0].sumAmount = row.sumAmount
  } else if (isCargoSpaceManage == 0) {
    if (row.codeType === 1 || row.codeType === 4) {
      row.calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(
          row.largeUnitQty || 0,
          row.unitConvertCoefficient || 1
        ),
        row.smallUnitQty || 0
      )
      row.qty = proxy.$fn.accDiv(
        row.calcQty || 0,
        row.unitConvertCoefficient || 1
      )
      row.sumAmount = proxy.$fn.accDiv(
        proxy.$fn.accMul(row.calcQty || 0, parseFloat(row.price || 0)),
        row.unitConvertCoefficient || 1
      )
      row.details[0].largeUnitQty = row.largeUnitQty
      row.details[0].smallUnitQty = row.smallUnitQty
      row.details[0].calcQty = row.calcQty
      row.details[0].qty = row.qty
      row.details[0].sumAmount = row.sumAmount
    }
  }
}
function changeSmall(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  if (row.codeType === 1 || row.codeType === 4) {
    row.calcQty = proxy.$fn.accAdd(
      proxy.$fn.accMul(row.largeUnitQty || 0, row.unitConvertCoefficient || 1),
      row.smallUnitQty || 0
    )
    row.qty = proxy.$fn.accDiv(
      row.calcQty || 0,
      row.unitConvertCoefficient || 1
    )
    row.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(row.calcQty || 0, parseFloat(row.price || 0)),
      row.unitConvertCoefficient || 1
    )
    row.details[0].largeUnitQty = row.largeUnitQty
    row.details[0].smallUnitQty = row.smallUnitQty
    row.details[0].calcQty = row.calcQty
    row.details[0].qty = row.qty
    row.details[0].sumAmount = row.sumAmount
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function countData(data) {
  if (data.stockAvailableCalcQty > data.unitConvertCoefficient) {
    data.calcQty = data.unitConvertCoefficient
    data.largeUnitQty = parseInt(data.calcQty / data.unitConvertCoefficient)
    data.smallUnitQty = parseInt(data.calcQty % data.unitConvertCoefficient)
    data.qty = proxy.$fn.accDiv(data.calcQty, data.unitConvertCoefficient)
    data.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(data.calcQty, data.price),
      data.unitConvertCoefficient
    )
  } else {
    data.calcQty = data.stockAvailableCalcQty
    data.largeUnitQty = parseInt(data.calcQty / data.unitConvertCoefficient)
    data.smallUnitQty = parseInt(data.calcQty % data.unitConvertCoefficient)
    data.qty = proxy.$fn.accDiv(data.calcQty, data.unitConvertCoefficient)
    data.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(data.calcQty, data.price),
      data.unitConvertCoefficient
    )
  }
  data._key =
    data.batchNumber +
    '-' +
    data.productionDate +
    '-' +
    data.validityDate +
    '-' +
    data.storeBatchNumber +
    '-' +
    data.supplierId +
    '-' +
    data.price +
    '-' +
    data.isConsignBusiness
  productIdMap.value[data.supplierId] = 1

  return data
}
function tableCellClassName({ column, row }) {
  if (row.isChoice && column.property === 'qty') {
    return 'success-row'
  } else {
    return ''
  }
}
function addBucth(row, index) {
  batchNumberSearch(row, index)
}
function removeProduct() {
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      let productIds = tableInfo.selections.map((item) => item.productId)
      tableInfo.data = tableInfo.data.filter(
        (item) => !productIds.includes(item.productId)
      )
      if (!tableInfo.data.length) {
        tableInfo.data = [
          {
            emptyRowType: '1',
            productKeyword: '',
            batchKeyword: '',
            id: new Date().getTime() + (1 + Math.random()),
          },
        ]
      } else {
        let index = tableInfo.data.findIndex(
          (item) => item.emptyRowType === '1'
        )
        if (index === -1) {
          tableInfo.data.push({
            emptyRowType: '1',
            productKeyword: '',
            batchKeyword: '',
            id: new Date().getTime() + (1 + Math.random()),
          })
        }
      }
      const data = proxy.$fn.deepClone(tableInfo.data)
      tableInfo.data = []
      proxy.$nextTick(() => {
        tableInfo.data = data
      })
    })
}
// 用于存储productId对应批次数量
const productIdMap = ref({})
function setSuplierIdMap() {
  let _data = tableInfo.data.filter((element) => {
    return element.productId
  })
  productIdMap.value = _.groupBy(_data, 'productId')
}
function removeBatch(row, index) {
  let isCargoSpaceManage = infoList.data.isCargoSpaceManage //1货位管理，0非货位管理
  if (row.codeType === 1 || row.codeType === 4) {
    if (
      productIdMap.value[row.productId] &&
      productIdMap.value[row.productId]?.length > 1
    ) {
      tableInfo.data = tableInfo.data.filter((item) => ![row].includes(item))
    } else {
      tableInfo.data[index] = {
        commonName: row.commonName,
        productCode: row.productCode,
        groupConcatIds: row.groupConcatIds,
        standard: row.standard,
        brandName: row.brandName,
        brandId: row.brandId,
        unitName: row.unitName,
        unitId: row.unitId,
        codeTypeValue: row.codeTypeValue,
        codeType: row.codeType,
        productId: row.productId,
        applicationQty: row.applicationQty,
        availableQty: row.availableQty,
        applicationCalcQty: row.applicationCalcQty,
        availableCalcQty: row.availableCalcQty,
        emptyRowType: '2',
      }
    }
  } else if (row.codeType === 2 || row.codeType === 3) {
    if (isCargoSpaceManage == 1) {
      if (
        productIdMap.value[row.productId] &&
        productIdMap.value[row.productId]?.length > 1
      ) {
        tableInfo.data = tableInfo.data.filter((item) => ![row].includes(item))
      } else {
        tableInfo.data[index] = {
          commonName: row.commonName,
          productCode: row.productCode,
          groupConcatIds: row.groupConcatIds,
          standard: row.standard,
          brandName: row.brandName,
          brandId: row.brandId,
          unitName: row.unitName,
          unitId: row.unitId,
          codeTypeValue: row.codeTypeValue,
          codeType: row.codeType,
          productId: row.productId,
          applicationQty: row.applicationQty,
          availableQty: row.availableQty,
          applicationCalcQty: row.applicationCalcQty,
          availableCalcQty: row.availableCalcQty,
          emptyRowType: '2',
        }
      }
    } else if (isCargoSpaceManage == 0) {
      tableInfo.data[index] = {
        commonName: row.commonName,
        productCode: row.productCode,
        groupConcatIds: row.groupConcatIds,
        standard: row.standard,
        brandName: row.brandName,
        brandId: row.brandId,
        unitName: row.unitName,
        unitId: row.unitId,
        codeTypeValue: row.codeTypeValue,
        codeType: row.codeType,
        productId: row.productId,
        applicationQty: row.applicationQty,
        availableQty: row.availableQty,
        applicationCalcQty: row.applicationCalcQty,
        availableCalcQty: row.availableCalcQty,
        emptyRowType: '2',
      }
      let list = tableInfo.data.filter(
        (item) => item.productId === row.productId
      )
      tableInfo.data = tableInfo.data.filter((item, i) => {
        if (!list.includes(item) || index === i) {
          return item
        }
      })
    }
  }
}
function individualDetails(row, index) {
  let list = tableInfo.data.filter((item) => item.productId === row.productId)
  let ids = []
  let details = []
  if (list.length) {
    list.forEach((item) => {
      if (item.details && item.details.length) {
        item.details.forEach((item) => {
          ids.push(item.depotStockId)
        })
        details = details.concat(item.details)
      }
    })
  }
  individualInfo.value.row = row
  individualInfo.value.details = details
  individualInfo.value.index = index
  individualInfo.value.leftQuery.queryMap.orgId.value = row.orgId
  individualInfo.value.leftQuery.queryMap.productId.value = row.productId
  individualInfo.value.leftQuery.queryMap.id.value = ids ? ids.toString() : ''
  individualInfo.value.visible = true
}
function individualCallback(data) {
  let index = individualInfo.value.index
  let row = individualInfo.value.row
  if (data.length) {
    data.forEach((item) => {
      item.orderSourceDetailId = row['orderSourceDetailId']
      item = countData(item)
    })
    let groupData = _.groupBy(data, '_key')
    let productIds = Object.keys(groupData)
    let productIdsIn = []
    let commonName = []
    tableData.value.forEach((row) => {
      let allCalcQty = 0
      data.forEach((item) => {
        if (item.productId === row.productId) {
          allCalcQty = proxy.$fn.accAdd(item.calcQty || 0, allCalcQty)
        }
      })
      if (row.availableCalcQty < allCalcQty) {
        commonName.push(row.commonName)
      }
    })
    if (commonName.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: `产品【${commonName}】出库数量大于待出数，请修改！`,
      })
    }
    tableInfo.data = tableInfo.data.filter((item) => {
      if (item.productId === row.productId) {
        if (item._key) {
          return productIds.includes(item._key)
        } else {
          return item
        }
      } else {
        return item
      }
    })
    tableInfo.data.forEach((item) => {
      if (item.productId === row.productId) {
        if (item._key) {
          if (productIds.includes(item._key)) {
            productIdsIn.push(item._key)
            item.details = groupData[item._key]
            item = countQty(item)
          }
        }
      }
    })
    let list = []
    if (productIdsIn.length) {
      productIds.forEach((item) => {
        if (!productIdsIn.includes(item)) {
          let groupDataItem = groupData[item]
          let obj = proxy.$fn.deepClone(groupDataItem[0])
          obj.details = proxy.$fn.deepClone(groupDataItem)
          obj.groupConcatIds = row.groupConcatIds
          obj.productId = row.productId
          obj = countQty(obj)
          obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
          obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
          obj.applicationQty = row.applicationQty
          obj.availableQty = row.availableQty
          obj.applicationCalcQty = row.applicationCalcQty
          obj.availableCalcQty = row.availableCalcQty
          list.push(obj)
        }
      })
    } else {
      let values = Object.values(groupData)
      values.forEach((item) => {
        let obj = proxy.$fn.deepClone(item[0])
        obj.details = proxy.$fn.deepClone(item)
        obj.groupConcatIds = row.groupConcatIds
        obj.productId = row.productId
        obj = countQty(obj)
        obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
        obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
        obj.applicationQty = row.applicationQty
        obj.availableQty = row.availableQty
        obj.applicationCalcQty = row.applicationCalcQty
        obj.availableCalcQty = row.availableCalcQty
        list.push(obj)
      })
    }
    if (list.length) {
      let newData = tableInfo.data[index]
      let leftList = []
      if (newData._key) {
        leftList = tableInfo.data.slice(0, index + 1)
      } else {
        leftList = tableInfo.data.slice(0, index)
      }
      let rightList = tableInfo.data.slice(index + 1)
      tableInfo.data = leftList.concat(list).concat(rightList)
    }
  } else {
    tableInfo.data[index] = {
      commonName: row.commonName,
      productCode: row.productCode,
      groupConcatIds: row.groupConcatIds,
      standard: row.standard,
      brandName: row.brandName,
      brandId: row.brandId,
      unitName: row.unitName,
      unitId: row.unitId,
      codeTypeValue: row.codeTypeValue,
      codeType: row.codeType,
      productId: row.productId,
      applicationQty: row.applicationQty,
      availableQty: row.availableQty,
      applicationCalcQty: row.applicationCalcQty,
      availableCalcQty: row.availableCalcQty,
      emptyRowType: '2',
    }
    tableInfo.data = tableInfo.data.filter((item) => {
      if (row.productId === item.productId) {
        return item.emptyRowType === '2'
      } else {
        return item
      }
    })
  }
  let emptyIndex = tableInfo.data.findIndex((item) => item.emptyRowType === '1')
  if (emptyIndex === -1) {
    tableInfo.data.push({
      emptyRowType: '1',
      productKeyword: '',
      batchKeyword: '',
      id: new Date().getTime() + (1 + Math.random()),
    })
  }
}
function onCallBackScanData(data, callback) {
  let { mergeDetail, detail } = data
  let productIds = applicationDetailProductIds.value
  if (productIds.indexOf(detail.productId) == -1) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请扫描申请的产品！',
    })
    return
  }
  let tableDataItem = tableData.value.find(
    (item) => item.productId === detail.productId
  )
  mergeDetail = mergeDetail[0]
  mergeDetail.applicationQty = tableDataItem.applicationQty
  mergeDetail.applicationCalcQty = tableDataItem.applicationCalcQty
  mergeDetail.availableQty = tableDataItem.availableQty
  mergeDetail.availableCalcQty = tableDataItem.availableCalcQty
  mergeDetail.orderSourceDetailId = tableDataItem.orderSourceDetailId
  detail.orderSourceDetailId = tableDataItem.orderSourceDetailId
  detail._key =
    detail.batchNumber +
    '-' +
    detail.productionDate +
    '-' +
    detail.validityDate +
    '-' +
    detail.storeBatchNumber +
    '-' +
    detail.supplierId +
    '-' +
    detail.price +
    '-' +
    detail.isConsignBusiness
  let unitConvertCoefficient = detail.unitConvertCoefficient || 1
  if (tableInfo.data && tableInfo.data.length) {
    tableInfo.data.forEach((item) => {
      item.isChoice = false
    })
    let list = tableInfo.data.filter(
      (item) => item.productId === mergeDetail.productId
    )
    if (list.length) {
      let allCalcQty = 0
      list.forEach((item) => {
        allCalcQty = proxy.$fn.accAdd(item.calcQty || 0, allCalcQty)
      })
      if (list[0].availableCalcQty <= allCalcQty) {
        proxy.$message({
          duration: 3500,
          type: 'warning',
          showClose: true,
          message: '当前扫描产品出库数量不能大于待出数！',
        })
        return
      }
      let index = tableInfo.data.findIndex(
        (item) =>
          item.productId === mergeDetail.productId &&
          item._key &&
          item._key === detail._key
      )
      if (index > -1) {
        if (
          tableInfo.data[index].calcQty ===
          tableInfo.data[index].stockAvailableCalcQty
        ) {
          callback(true)
          return
        }
        let haveIndex = tableInfo.data[index].details.findIndex(
          (item) => item.depotStockId == detail.depotStockId
        )
        if (detail.codeType === 2 || detail.codeType === 3) {
          if (haveIndex > -1) {
            callback(true)
          } else {
            tableInfo.data[index].details.push(detail)
            tableInfo.data[index] = countQty(tableInfo.data[index])
            tableInfo.data[index].isChoice = true
          }
        } else if (detail.codeType === 4) {
          let num = proxy.$fn.Subtr(
            tableInfo.data[index].stockAvailableCalcQty,
            tableInfo.data[index].calcQty
          )
          if (haveIndex > -1) {
            if (num > unitConvertCoefficient) {
              tableInfo.data[index].details[haveIndex].calcQty =
                proxy.$fn.accAdd(
                  tableInfo.data[index].details[haveIndex].calcQty || 0,
                  1
                )
            } else {
              tableInfo.data[index].details[haveIndex].calcQty =
                tableInfo.data[index].details[haveIndex].stockAvailableCalcQty
            }
            tableInfo.data[index].details[haveIndex].largeUnitQty = parseInt(
              tableInfo.data[index].details[haveIndex].calcQty /
                unitConvertCoefficient
            )
            tableInfo.data[index].details[haveIndex].smallUnitQty = parseInt(
              tableInfo.data[index].details[haveIndex].calcQty %
                unitConvertCoefficient
            )
            tableInfo.data[index].details[haveIndex].qty = proxy.$fn.accDiv(
              tableInfo.data[index].details[haveIndex].calcQty,
              unitConvertCoefficient
            )
            tableInfo.data[index].details[haveIndex].sumAmount =
              proxy.$fn.accDiv(
                proxy.$fn.accMul(
                  tableInfo.data[index].details[haveIndex].calcQty,
                  tableInfo.data[index].details[haveIndex].price
                ),
                unitConvertCoefficient
              )
            tableInfo.data[index] = countQty(tableInfo.data[index])
            tableInfo.data[index].isChoice = true
          } else {
            tableInfo.data[index].details.push(detail)
            tableInfo.data[index] = countQty(tableInfo.data[index])
            tableInfo.data[index].isChoice = true
          }
        }
      } else {
        let newIndex = tableInfo.data.findIndex(
          (item) =>
            item.productId === mergeDetail.productId &&
            item.emptyRowType &&
            item.emptyRowType === '2'
        )
        if (newIndex > -1) {
          mergeDetail.details = [detail]
          mergeDetail._key = detail._key
          mergeDetail = countQty(mergeDetail)
          tableInfo.data[newIndex] = mergeDetail
        } else {
          let spliceIndex = tableInfo.data.findIndex(
            (item) => item.depotStockId == list[list.length - 1].depotStockId
          )
          mergeDetail.details = [detail]
          mergeDetail._key = detail._key
          mergeDetail = countQty(mergeDetail)
          tableInfo.data.splice(spliceIndex, 0, mergeDetail)
        }
      }
    } else {
      mergeDetail.details = [detail]
      mergeDetail._key = detail._key
      mergeDetail = countQty(mergeDetail)
      tableInfo.data.unshift(mergeDetail)
      callback(false)
    }
  }
  setSuplierIdMap()
}
function submitAndexport() {
  submit(true)
}
function submit(isSubmitAndexport = false) {
  console.log(1111111111)
  console.log(isSubmitAndexport)
  proxy.$fn.checkForm(formRefs.value).then(() => {
    if (tableInfo.data.length === 0) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '出库明细不能为空',
      })
      return
    } else {
      let emptyDetails = tableInfo.data
        .filter((item) => item.emptyRowType === '2')
        .map((item) => item.commonName)
      if (emptyDetails.length) {
        proxy.$message({
          message: '请添产品【' + emptyDetails + '】的批次信息',
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
        return
      }
      const qtyZero = tableInfo.data
        .filter((item) => item.qty > 0)
        .map((item) => item.commonName)
      if (!qtyZero.length) {
        proxy.$alert(`产品【${qtyZero}】出库数量不能为0`, '操作提示', {
          confirmButtonText: '确定',
        })
        return
      }
      let commonName = []
      tableData.value.forEach((row) => {
        let allCalcQty = 0
        tableInfo.data.forEach((item) => {
          if (item.calcQty > 0 && row.productId === item.productId) {
            allCalcQty = proxy.$fn.accAdd(item.calcQty || 0, allCalcQty)
          }
        })
        if (row.availableCalcQty < allCalcQty) {
          commonName.push(row.commonName)
        }
      })
      if (commonName.length) {
        proxy.$message({
          duration: 3500,
          type: 'warning',
          showClose: true,
          message: `产品【${commonName}】出库数量大于待出数，请修改！`,
        })
        return
      }
      if (systemConfig.value.optimal_validate == 1) {
        let params = []
        tableInfo.data.forEach((item) => {
          if (!item.emptyRowType) {
            params.push({
              calcQty: item.calcQty || '',
              depotStockId: item.depotStockId || '',
            })
          }
        })
        depotStockValidateOptimalValidate(params).then((res) => {
          if (res && res.code && res.code == 200) {
            reSave(isSubmitAndexport)
          }
        })
      } else {
        reSave(isSubmitAndexport)
      }
    }
  })
}
function reSave(isSubmitAndexport) {
  let mergeDetail = tableInfo.data.filter((item) => item.calcQty > 0)
  let newDatas = {
    storeDeptId: infoList.data.deptId,
    storeDepotId: infoList.data.depotId,
    ...infoList.data,
    mergeDetails: proxy.$fn.filterBlacklist(mergeDetail),
    ...infoList.data,
  }
  const api = isSubmitAndexport ? commitAndBatchOutBound : createUseExport
  getCoreSystemConfigAll().then((resp) => {
    if (resp && resp.success) {
      let find = resp.data.find(
        (item) => item.systemConfigCode === 'allow_expire_out'
      )
      if (find) {
        let expire = validateExpire(tableInfo.data)
        if (find.value === '1') {
          if (expire) {
            proxy
              .$confirm(expire + ',是否继续?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                dangerouslyUseHTMLString: true,
              })
              .then(() => {
                api(newDatas).then((resp) => {
                  if (resp && resp.success) {
                    showDialog.value = false
                    emit('returnModify')
                  }
                })
                return
              })
              .catch(() => {
                return
              })
          } else {
            api(newDatas).then((resp) => {
              if (resp && resp.success) {
                showDialog.value = false
                emit('returnModify')
              }
            })
            return
          }
        } else {
          if (expire) {
            proxy.$alert(expire + '，不允许出库！', '操作提示', {
              confirmButtonText: '确定',
              dangerouslyUseHTMLString: true,
            })
            return
          } else {
            api(newDatas).then((resp) => {
              if (resp && resp.success) {
                showDialog.value = false
                emit('returnModify')
              }
            })
            return
          }
        }
      } else {
        api(newDatas).then((resp) => {
          if (resp && resp.success) {
            showDialog.value = false
            emit('returnModify')
          }
        })
        return
      }
    }
  })
}
function validateExpire(list = []) {
  let currentDate = moment().format('YYYY-MM-DD')
  let msg = ''
  list.forEach((item, index) => {
    if (item.validityDate && moment(item.validityDate).isBefore(currentDate)) {
      msg = msg + `第【${index + 1}】行产品【${item.commonName}】已过期，<br>`
    }
  })
  return msg
}
function getList() {
  //修改请求明细信息
  getUseApplicationDetail(detailFilterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      if (resp.data && resp.data.length) {
        //获取产品ID
        let productIds = []
        let arr = []
        resp.data.forEach((row) => {
          row.orderSourceDetailId = row.id
          //当可出库数量小于等于0的时候，产品不再添加到弹框搜索列表中
          if (row.qty > row.preExportQty) {
            productIds.push(row.productId)
            arr.push({
              commonName: row.commonName,
              productCode: row.productCode,
              groupConcatIds: row.groupConcatIds,
              standard: row.standard,
              brandName: row.brandName,
              brandId: row.brandId,
              unitName: row.unitName,
              unitId: row.unitId,
              codeTypeValue: row.codeTypeValue,
              codeType: row.codeType,
              productId: row.productId,
              applicationQty: row.applicationQty,
              availableQty: row.availableQty,
              applicationCalcQty: row.applicationCalcQty,
              availableCalcQty: row.availableCalcQty,
              emptyRowType: '2',
              orderSourceDetailId: row.id,
            })
          }
        })
        tableInfo.data = arr
        tableInfo.data.push({
          emptyRowType: '1',
          productKeyword: '',
          batchKeyword: '',
          id: new Date().getTime() + (1 + Math.random()),
        })
        applicationDetailProductIds.value = String(productIds)
        tableData.value = resp.data
      }
    } else {
      tableInfo.data = []
      tableData.value = []
    }
  })
}
function getMain() {
  getUseApplication(props.id).then((resp) => {
    if (resp && resp.success) {
      if (resp.data.depotName) {
        infoList.fieldList.forEach((item) => {
          if (item.value === 'depotName') {
            item.type = 'text'
          }
        })
      } else {
        infoList.fieldList.forEach((item) => {
          if (item.value === 'depotName') {
            item.type = 'slot'
          }
        })
      }
      infoList.data = resp.data
      infoList.supDepotIds = resp.data.supDepotIds || []
      scanInfo.query.queryParams.depotId = resp.data.exportDepotId
      selectBatchInfo.value.query.queryMap.depotId.value =
        resp.data.exportDepotId
      individualInfo.value.leftQuery.queryMap.depotId.value =
        resp.data.exportDepotId
      scanInfo.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      selectProductInfo.value.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      selectBatchInfo.value.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      individualInfo.value.leftQuery.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      individualInfo.value.rightQuery.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      detailFilterInfo.value.query.queryParams.isCargoSpaceManage =
        resp.data.isCargoSpaceManage
      filterInfo.list.forEach((item) => {
        if (resp.data.isCargoSpaceManage == 1) {
          if (
            item.value === 'receivingCodeScan'
            //  ||
            // item.value === 'smartRecommendation'
          ) {
            item.show = false
          }
        } else if (resp.data.isCargoSpaceManage == 0) {
          if (
            item.value === 'receivingCodeScan'
            //  ||
            // item.value === 'smartRecommendation'
          ) {
            item.show = true
          }
        }
      })
      if (resp.data.isCargoSpaceManage == 1) {
        selectBatchInfo.value.tableKey =
          'useApplicationOrderRatifyWmsBatch-com.slip.spd.entity.vo.stock.DepotStockVO'
      } else if (resp.data.isCargoSpaceManage == 0) {
        selectBatchInfo.value.tableKey =
          'useApplicationOrderRatifyBatch-com.slip.spd.entity.vo.stock.DepotStockVO'
      }
      getProductCustomize()
      setBusinessDate()
      if (resp.data.exportDepotId == -2) {
        getDefaultDeopt(resp.data)
      }
    }
  })
}
function getDefaultDeopt(params) {
  getUseAuditGetDefaultExportDepot(params).then((res) => {
    if (res && res.success) {
      if (res.data && res.data.exportDepotId) {
        infoList.data.exportDepotId = res.data.exportDepotId
        infoList.data.exportDepotName = res.data.exportDepotName
        infoList.data.exportDeptId = res.data.exportDeptId
        infoList.data.exportDeptIdName = res.data.exportDeptIdName
        individualInfo.value.leftQuery.queryMap.depotId.value =
          res.data.exportDepotId
        scanInfo.query.queryParams.depotId = res.data.exportDepotId
        selectBatchInfo.value.query.queryMap.depotId.value =
          res.data.exportDepotId
      } else {
        infoList.data.exportDepotId = ''
        infoList.data.exportDepotName = ''
        infoList.data.exportDeptName = ''
        infoList.data.exportDeptId = ''
        individualInfo.value.leftQuery.queryMap.depotId.value = ''
        scanInfo.query.queryParams.depotId = ''
        selectBatchInfo.value.query.queryMap.depotId.value = ''
      }
    }
  })
}
function _smartRecommendation() {
  let params = {
    ...infoList.data,
    mergeDetails: tableInfo.data.filter((item) => item._key),
  }
  let tableInfoDataTemp = proxy.$fn.deepClone(tableInfo.data)
  tableInfo.data = []
  smartRecommendation(params).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data

      if (data && data.length) {
        data.forEach((item) => {
          if (item.codeType === 1 || item.codeType === 4) {
            item._key =
              item.batchNumber +
              '-' +
              item.productionDate +
              '-' +
              item.validityDate +
              '-' +
              item.storeBatchNumber +
              '-' +
              item.supplierId +
              '-' +
              item.price +
              '-' +
              item.isConsignBusiness
            item._id =
              item.productId +
              '-' +
              item.batchNumber +
              '-' +
              item.productionDate +
              '-' +
              item.validityDate +
              '-' +
              item.storeBatchNumber +
              '-' +
              item.supplierId +
              '-' +
              item.price +
              '-' +
              item.isConsignBusiness
          } else if (item.codeType === 2 || item.codeType === 3) {
            if (item.details && item.details.length) {
              item._key =
                item.batchNumber +
                '-' +
                item.productionDate +
                '-' +
                item.validityDate +
                '-' +
                item.storeBatchNumber +
                '-' +
                item.supplierId +
                '-' +
                item.price +
                '-' +
                item.isConsignBusiness
            }

            item._id =
              item.productId +
              '-' +
              item.batchNumber +
              '-' +
              item.productionDate +
              '-' +
              item.validityDate +
              '-' +
              item.storeBatchNumber +
              '-' +
              item.supplierId +
              '-' +
              item.price +
              '-' +
              item.isConsignBusiness
          }
        })
        let groupData = _.groupBy(data, '_id')
        let groupDataValue = Object.values(groupData)
        let newArr = []
        groupDataValue.forEach((row) => {
          let arr = proxy.$fn.deepClone(row)
          let obj = arr[0]
          let calcQty = 0
          let largeUnitQty = 0
          let smallUnitQty = 0
          let sumAmount = 0
          let stockAvailableCalcQty = 0
          let tableDataItem = tableData.value.find(
            (item) => item.productId === row[0].productId
          )
          arr.forEach((item) => {
            largeUnitQty = proxy.$fn.accAdd(
              largeUnitQty,
              item.largeUnitQty || 0
            )
            smallUnitQty = proxy.$fn.accAdd(
              smallUnitQty,
              item.smallUnitQty || 0
            )
            sumAmount = proxy.$fn.accAdd(sumAmount, item.sumAmount || 0)
            calcQty = proxy.$fn.accAdd(calcQty, item.calcQty || 0)
            stockAvailableCalcQty = proxy.$fn.accAdd(
              stockAvailableCalcQty,
              item.stockAvailableCalcQty || 0
            )
          })
          obj['largeUnitQty'] = largeUnitQty
          obj['smallUnitQty'] = smallUnitQty
          obj['calcQty'] = calcQty
          obj['stockAvailableCalcQty'] = stockAvailableCalcQty
          obj['sumAmount'] = sumAmount
          let qty = proxy.$fn.accDiv(calcQty, obj.unitConvertCoefficient)
          let stockAvailableQty = proxy.$fn.accDiv(
            stockAvailableCalcQty,
            obj.unitConvertCoefficient
          )
          obj['qty'] = qty
          obj['stockAvailableQty'] = stockAvailableQty
          if (row[0].emptyRowType !== '2') {
            if (row[0].codeType === 1 || row[0].codeType === 4) {
              obj['details'] = row
            }
          } else {
            obj['details'] = []
          }
          obj['applicationQty'] = tableDataItem.applicationQty
          obj['availableQty'] = tableDataItem.availableQty
          obj['applicationCalcQty'] = tableDataItem.applicationCalcQty
          obj['availableCalcQty'] = tableDataItem.availableCalcQty
          obj['orderSourceDetailId'] = tableDataItem.id
          newArr.push(obj)
        })
        tableInfo.data = proxy.$fn.getSort(newArr, 'productId', 'desc')
      }
      tableInfo.data.push({
        emptyRowType: '1',
        productKeyword: '',
        batchKeyword: '',
        id: new Date().getTime() + (1 + Math.random()),
      })
    } else {
      tableInfo.data = tableInfoDataTemp
    }
  })
}
//导出excel
function exportExcel() {
  exportUseApplication(infoList.data.id).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
//打印
function print() {
  printUseApplication(infoList.data.id).then((resp) => {
    if (resp && resp.success) {
      proxy.$print.printOrder(resp.data)
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'useApplicationOrderRatifyProductBatchModify-com.slip.spd.entity.vo.stock.TransferOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let arr = []
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          arr.push(key)
        }
      }
      selectBatchInfo.value.query.queryParams.groupField = arr.length
        ? arr.toString()
        : ''
      individualInfo.value.leftQuery.queryParams.groupField = arr.length
        ? arr.toString()
        : ''
      tableInfo.sysGroup = arr
      if (props.id) {
        getMain()
      } else {
        setBusinessDate()
      }
    }
  })
}
function getScanCustomize() {
  let param = {
    tableKey:
      'useApplicationOrderRatifyProductBatchScan-com.slip.spd.entity.vo.stock.DepotStockVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      scanInfo.query.customizeUserVO = data
    }
  })
}
function getProductCustomize() {
  let param = {
    tableKey:
      'useApplicationOrderRatifyProduct-com.slip.spd.entity.vo.use.UseApplicationOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      detailFilterInfo.value.query.customizeUserVO = res.data
      getList()
    }
  })
}
getCustomize()
getScanCustomize()
</script>
<style lang="scss" scoped>
.el-input-search {
  width: 100%;
  height: 100%;
}
.isShow {
  :deep(.el-scrollbar__wrap) {
    overflow: inherit;
  }
}
.el-popper {
  overflow-y: hidden;
}
</style>
<style>
.el-popper {
  max-height: max-content !important;
}
</style>
